package com.daervin.svc.manager;

import com.daervin.svc.common.dto.WhSupplierDTO;
import com.daervin.svc.dal.WhSupplierMapper;
import com.daervin.svc.dal.model.WhSupplierDO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created by daervin on 2023/8/18
 */
@Component
public class SupplierManager {

    @Resource
    private WhSupplierMapper whSupplierMapper;

    public List<WhSupplierDTO> getSupplier() {
        List<WhSupplierDO> supplierDOList = whSupplierMapper.selectAll();
        if (CollectionUtils.isEmpty(supplierDOList)) {
            return Collections.emptyList();
        }
        return supplierDOList.stream().map(it -> {
            WhSupplierDTO s = new WhSupplierDTO();
            BeanUtils.copyProperties(it, s);
            return s;
        }).collect(Collectors.toList());
    }

    public Map<Long, WhSupplierDTO> getSupplierMap() {
        List<WhSupplierDTO> list = getSupplier();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        return list.stream().collect(Collectors.toMap(WhSupplierDTO::getId, Function.identity(), (k1, k2) -> k2));
    }

    public WhSupplierDTO match(Long id) {
        List<WhSupplierDTO> list = getSupplier();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.stream().filter(it -> it.getId().compareTo(id) == 0).findFirst().orElse(null);
    }

    public boolean addOrUpdate(WhSupplierDTO supplierDTO) {
        WhSupplierDO record = new WhSupplierDO();
        record.setId(supplierDTO.getId());
        record.setName(supplierDTO.getName());
        record.setExt(supplierDTO.getExt());
        record.setUpdateTime(new Date());
        if (supplierDTO.getId() != null && supplierDTO.getId() > 0) {
            whSupplierMapper.updateByPrimaryKeySelective(record);
            return true;
        }
        record.setCreateTime(new Date());
        whSupplierMapper.insertSelective(record);
        return true;
    }
}
